package net.expectx.pay.merchant.controller;

import com.github.wxpay.sdk.WXPayConfig;
import io.swagger.annotations.ApiOperation;
import net.expectx.common.single.base.BaseConstants;
import net.expectx.common.single.base.BaseResult;
import net.expectx.pay.core.common.EXPayResult;
import net.expectx.pay.core.micro.WeiXinMicroMerchantServicesUtil;
import net.expectx.pay.dao.bean.*;
import net.expectx.pay.merchant.common.AdminConstants;
import net.expectx.pay.merchant.common.AdminResult;
import net.expectx.pay.merchant.common.util.ExpectXUtil;
import net.expectx.pay.rpc.api.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author hxs
 */

@Controller
@RequestMapping("/merchantApplication")
public class MerchantApplicationController {

    @Autowired
    private MerchantApplicationService merchantApplicationService;
    @Autowired
    private PaymentChannelService paymentChannelService;
    @Autowired
    private SystemTypeService systemTypeService;
    @Autowired
    private MerchantPaymentConfigService merchantPaymentConfigService;
    @Autowired
    private MerchantWeixinSignService merchantWeixinSignService;

    @ApiOperation(value = "应用管理主页")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "merchantApplication/index";
    }

    @ApiOperation(value = "新增应用管理")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(ModelMap modelMap) {
        PaymentChannelExample paymentChannelExample = new PaymentChannelExample();
        paymentChannelExample.createCriteria().andIsDeletedEqualTo(AdminConstants.NO);
        List<PaymentChannel> paymentChannels = paymentChannelService.selectByExample(paymentChannelExample);
        modelMap.put("paymentChannels", paymentChannels);
        return "merchantApplication/modify";
    }

    @ApiOperation(value = "修改应用管理")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String update(@PathVariable("id") Long id, ModelMap modelMap) {
        MerchantApplication merchantApplication = merchantApplicationService.selectByPrimaryKey(id);
        modelMap.put("merchantApplication", merchantApplication);
        PaymentChannelExample paymentChannelExample = new PaymentChannelExample();
        paymentChannelExample.createCriteria().andIsDeletedEqualTo(AdminConstants.NO);
        List<PaymentChannel> paymentChannels = paymentChannelService.selectByExample(paymentChannelExample);
        modelMap.put("paymentChannels", paymentChannels);
        return "merchantApplication/modify";
    }

    @ApiOperation(value = "应用参数配置")
    @RequestMapping(value = "/config/{id}", method = RequestMethod.GET)
    public String config(@PathVariable("id") Long id, ModelMap modelMap) {

        MerchantApplication merchantApplication = merchantApplicationService.selectByPrimaryKey(id);
        modelMap.put("merchantApplication", merchantApplication);
        List<Long> paymentChannelIds = new ArrayList<>();
        MerchantWeixinSignExample merchantWeixinSignExample = new MerchantWeixinSignExample();
        MerchantWeixinSignExample.Criteria criteria1= merchantWeixinSignExample.createCriteria();
        criteria1.andMerchantNoEqualTo(merchantApplication.getMerchantNo());
        List<MerchantWeixinSign> merchantWeixinSigns = merchantWeixinSignService.selectByExample(merchantWeixinSignExample);
        if(!merchantWeixinSigns.isEmpty()){
            modelMap.put("weixinSignStatus", merchantWeixinSigns.get(0).getStatus());
        }
        MerchantPaymentConfigExample merchantPaymentConfigExample = new MerchantPaymentConfigExample();
        MerchantPaymentConfigExample.Criteria criteria = merchantPaymentConfigExample.createCriteria();
        criteria.andMerchantNoEqualTo(merchantApplication.getMerchantNo());
        List<MerchantPaymentConfig> merchantPaymentConfigs = merchantPaymentConfigService.selectByExample(merchantPaymentConfigExample);

        String[] paymentChannelIdString = merchantApplication.getPaymentChannel().split(",");
        for (String s : paymentChannelIdString) {
            paymentChannelIds.add(Long.valueOf(s));
        }

        PaymentChannelExample paymentChannelExample = new PaymentChannelExample();
        paymentChannelExample.createCriteria().andIdIn(paymentChannelIds);
        paymentChannelExample.setOrderByClause("id asc");
        List<PaymentChannel> paymentChannels = paymentChannelService.selectByExample(paymentChannelExample);
        for (int i = 0; i < paymentChannels.size(); i++) {
            for (MerchantPaymentConfig merchantPaymentConfig : merchantPaymentConfigs) {
                if(merchantPaymentConfig.getPaymentChannel()==paymentChannels.get(i).getId()){
                    paymentChannels.get(i).setVerify(true);
                }
            }
        }
        modelMap.put("paymentChannels", paymentChannels);

        return "merchantApplication/config";
    }

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    @ResponseBody
    public Object page(
            @RequestParam(required = false, defaultValue = "1", value = "page") int page,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>(16);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MerchantUser merchantUser = (MerchantUser) session.getAttribute("merchantUser");

        String merchantApplicationName = request.getParameter("merchantApplicationName");
        MerchantApplicationExample merchantApplicationExample = new MerchantApplicationExample();
        /**
         * 创造条件
         */
        MerchantApplicationExample.Criteria criteria = merchantApplicationExample.createCriteria();
        criteria.andIsDeletedEqualTo(AdminConstants.NO);
        criteria.andMerchantNoEqualTo(merchantUser.getMerchantNo());
        if (StringUtils.isNotBlank(merchantApplicationName)) {
            criteria.andNameLike(merchantApplicationName + "%");
        }
        /**
         * 分页
         */
        merchantApplicationExample.setPageIndex(page);
        merchantApplicationExample.setPageSize(limit);
        /**
         * 排序
         */
        merchantApplicationExample.setOrderByClause("gmt_modified desc");

        List<MerchantApplication> merchantApplications = merchantApplicationService.selectByExample(merchantApplicationExample);

        ArrayList<Long> longs = new ArrayList<>();
        longs.add(15L);
        longs.add(16L);
        SystemTypeExample systemTypeExample = new SystemTypeExample();
        SystemTypeExample.Criteria criteria1 = systemTypeExample.createCriteria();
        criteria1.andIsDeletedEqualTo(AdminConstants.NO);
        criteria1.andTypeGroupIdIn(longs);

        List<SystemType> systemTypes = systemTypeService.selectByExample(systemTypeExample);
        for (MerchantApplication merchantApplication : merchantApplications) {
            for (SystemType systemType : systemTypes) {
                if (systemType.getTypeGroupId().equals(15L) && merchantApplication.getScene().equals(systemType.getTypeCode())) {
                    merchantApplication.setScene(systemType.getTypeName());
                }
                if (systemType.getTypeGroupId().equals(16L) && merchantApplication.getType().equals(systemType.getTypeCode())) {
                    merchantApplication.setType(systemType.getTypeName());
                }
            }
        }
        long total = merchantApplicationService.countByExample(merchantApplicationExample);

        result.put("code", AdminConstants.LAYUI_DATA_OK);
        result.put("count", total);
        result.put("msg", "");
        result.put("data", merchantApplications);
        return result;
    }

    @ApiOperation(value = "新增应用管理")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(MerchantApplication merchantApplication, HttpServletRequest request) {
        String merchantNo = (String) request.getSession().getAttribute("merchantNo");

        String agentNo;
        MerchantApplicationExample merchantApplicationExample = new MerchantApplicationExample();
        merchantApplicationExample.createCriteria().andIsDeletedEqualTo(AdminConstants.NO);
        merchantApplicationExample.setOrderByClause("agent_no desc");
        List<MerchantApplication> merchantApplications = merchantApplicationService.selectByExample(merchantApplicationExample);
        if (merchantApplications.isEmpty()) {
            agentNo = merchantNo + "001";
        } else {
            String agentNo2 = merchantApplications.get(0).getAgentNo();
            int length = agentNo2.length();
            String substring = agentNo2.substring(length - 3, length);
            Format f1 = new DecimalFormat("000");
            agentNo = merchantNo + f1.format((Long.valueOf(substring)) + 1);
        }
        merchantApplication.setMerchantNo(merchantNo);
        merchantApplication.setAgentNo(agentNo);
        merchantApplication.setGmtCreate(System.currentTimeMillis());
        merchantApplication.setGmtModified(System.currentTimeMillis());
        merchantApplication.setIsDeleted(AdminConstants.NO);
        return merchantApplicationService.insertSelective(merchantApplication);
    }

    @ApiOperation(value = "修改应用管理")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@PathVariable("id") Long id, MerchantApplication merchantApplication) {
        merchantApplication.setGmtModified(System.currentTimeMillis());
        return merchantApplicationService.updateByPrimaryKeySelective(merchantApplication);
    }

    @ApiOperation(value = "删除应用管理")
    @RequestMapping(value = "/physicalRemove/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public Object physicalRemove(@PathVariable("ids") String ids) {
        MerchantApplicationExample merchantApplicationExample = new MerchantApplicationExample();
        merchantApplicationExample.createCriteria().andIdIn(ExpectXUtil.toList(ids, ","));
        BaseResult baseResult = merchantApplicationService.physicalRemoveByExample(AdminConstants.YES, merchantApplicationExample);
        return new AdminResult(baseResult);
    }

    @ApiOperation(value = "添加配置")
    @RequestMapping(value = "/addConfig/{id}", method = RequestMethod.GET)
    public String app(@PathVariable("id") Long id, Long merchantApplicationId, HttpServletRequest request) {
        PaymentChannel paymentChannel = paymentChannelService.selectByPrimaryKey(id);
        MerchantApplication merchantApplication = merchantApplicationService.selectByPrimaryKey(merchantApplicationId);
        request.setAttribute("merchantApplication", merchantApplication);
        request.setAttribute("paymentChannel", paymentChannel);
        return "merchantApplication/addConfig";
    }


    @ApiOperation(value = "应用管理主页")
    @RequestMapping(value = "/app/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Object app(@PathVariable("id") Long id,String appSecret,String appId,String merchantNo,String applicationNo,HttpServletRequest request) throws Exception {
        PaymentChannel paymentChannel = paymentChannelService.selectByPrimaryKey(id);
        MerchantPaymentConfigExample merchantPaymentConfigExample = new MerchantPaymentConfigExample();
        MerchantPaymentConfigExample.Criteria criteria = merchantPaymentConfigExample.createCriteria();
        MerchantWeixinSignExample merchantWeixinSignExample = new MerchantWeixinSignExample();
        MerchantWeixinSignExample.Criteria criteria2 = merchantWeixinSignExample.createCriteria();
        criteria2.andMerchantNoEqualTo(merchantNo);
        List<MerchantWeixinSign> merchantWeixinSigns = merchantWeixinSignService.selectByExample(merchantWeixinSignExample);
        String subMchId = "";
        if(!merchantWeixinSigns.isEmpty()){
            subMchId = merchantWeixinSigns.get(0).getMchId();
        }else{
            BaseResult baseResult1=new BaseResult(false,"没有mch_id",null);
            return baseResult1;
        }
        criteria.andAppIdEqualTo(appId);
        List<MerchantPaymentConfig> merchantPaymentConfigs = merchantPaymentConfigService.selectByExample(merchantPaymentConfigExample);
        if(merchantPaymentConfigs.isEmpty()){
            EXPayResult baseResult= WeiXinMicroMerchantServicesUtil.mchAddSubdevConfig(subMchId,appId);
            if(baseResult.isSuccess()){
                MerchantPaymentConfig merchantPaymentConfig = new MerchantPaymentConfig();
                merchantPaymentConfig.setGmtCreate(System.currentTimeMillis());
                merchantPaymentConfig.setGmtModified(System.currentTimeMillis());
                merchantPaymentConfig.setIsDeleted(BaseConstants.NO);
                merchantPaymentConfig.setAppId(appId);
                merchantPaymentConfig.setPrivateKey(appSecret);
                merchantPaymentConfig.setMchId(subMchId);
                merchantPaymentConfig.setMerchantNo(merchantNo);
                merchantPaymentConfig.setPayWay(paymentChannel.getName());
                merchantPaymentConfig.setPaymentChannel(id);
                merchantPaymentConfig.setApplicationNo(applicationNo);
                return merchantPaymentConfigService.insertSelective(merchantPaymentConfig);
            }else{
                BaseResult baseResult1=new BaseResult(false,baseResult.getMessage(),null);
                return baseResult1;
            }
        }else{
            return new BaseResult(false, "AppId已存在", null);
        }


    }
    @ApiOperation(value = "获取配置信息")
    @RequestMapping(value = "/getConfig/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Object getConfig(@PathVariable("id") Long id,String merchantNo) {
        MerchantPaymentConfigExample merchantPaymentConfigExample = new MerchantPaymentConfigExample();
        MerchantPaymentConfigExample.Criteria criteria = merchantPaymentConfigExample.createCriteria();
        criteria.andPaymentChannelEqualTo(id);
        criteria.andMerchantNoEqualTo(merchantNo);
        return merchantPaymentConfigService.selectByExample(merchantPaymentConfigExample).get(0);
    }

}
